package com.yeziji.security.common;

import cn.hutool.core.util.StrUtil;
import com.yeziji.common.Platform;
import com.yeziji.common.context.OnlineContext;
import com.yeziji.constant.VariousStrPool;
import com.yeziji.security.service.DynamicSecurityAuth;
import com.yeziji.utils.NanoIdUtils;
import com.yeziji.utils.expansion.Opt2;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Locale;

/**
 * 模拟在线上下文
 *
 * @author hwy
 * @since 2024/11/27 12:56
 **/
@Slf4j
@Component
public class MockOnlineContext {
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private DynamicSecurityAuth dynamicSecurityAuth;

    /**
     * 模拟登录到指定用户
     *
     * @param username 指定用户
     */
    public void mockLogin(String username) {
        String mdc = NanoIdUtils.randomNotSymbolNaoId();
        MDC.put(VariousStrPool.System.TRACE_ID, mdc);
        OnlineContext.setMdc(mdc);
        if (dynamicSecurityAuth != null) {
            Platform platform = dynamicSecurityAuth.getPlatform();
            OnlineContext.setPlatform(platform);
            OnlineContext.setLocale(Opt2.nullElse(platform.getPlatformLocale(), Locale.CHINA));
        }
        if (StrUtil.isNotBlank(username)) {
            try {
                IUserDetails userDetails = (IUserDetails) userDetailsService.loadUserByUsername(username);
                if (userDetails != null) {
                    OnlineContext.setOnlineUserDetails(userDetails);
                }
            } catch (Exception e) {
                log.warn("获取用户权限信息失败: {}", e.getMessage());
            }
        }
    }
}
